//
//  IMMessageReceiver.m
//  IMChezhil
//
//  Created by zhangliucheng on 15/7/27.
//  Copyright (c) 2015年 CheZhil. All rights reserved.
//

#import "IMMessageReceiver.h"

#define MessageReceiverNotification @"MessageReceiverNotification"
#define MessageSendResultNotification @"MessageSendResultNotification"


@interface IMMessageReceiver ()

@property (weak, nonatomic) id<IMMessageReceiverDelegate> messageReceiveDelegate;

@end

@implementation IMMessageReceiver

- (instancetype)init {
    self = [super init];
    if (self) {
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onMessageReceiver:) name:MessageReceiverNotification object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onMessageSendResult:) name:MessageSendResultNotification object:nil];
    }
    return self;
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self name:MessageReceiverNotification object:Nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:MessageSendResultNotification object:Nil];
}

- (void)onMessageReceiver:(NSNotification *)notification {
    IMUserMessage *message = notification.object;
    [self.messageReceiveDelegate receiveMessage:message];
}

- (void)onMessageSendResult:(NSNotification *)notification {
    IMUserMessage *message = notification.object;
    [self.messageReceiveDelegate sendMessageResult:message];
}

static IMMessageReceiver *messageReceiver;
+ (void)registerMessageDelegate:(id<IMMessageReceiverDelegate>)delegate {
    messageReceiver = Nil;
    messageReceiver = [IMMessageReceiver new];
    messageReceiver.messageReceiveDelegate = delegate;
}

+ (void)removeMessageDelegate {
    messageReceiver = Nil;
}

+ (void)postReceiveMessageNotification:(IMUserMessage *)message {
    [[NSNotificationCenter defaultCenter] postNotificationName:MessageReceiverNotification object:message];
}

+ (void)postSendMessageResultNotification:(IMUserMessage *)message {
    [[NSNotificationCenter defaultCenter] postNotificationName:MessageSendResultNotification object:message];
}
@end
